<template>
  <div class="com-container">
    <div class="com-chart" ref="hot_ref"></div>
    <span class="iconfont arr-left" @click="toLeft" :style="comStyle">&#xe6ef;</span>
    <span class="iconfont arr-right" @click="toRight" :style="comStyle">&#xe6ed;</span>
    <span class="cat-name" :style="comStyle">{{ catName }}</span>
  </div>
</template>

<script setup lang="ts">
import { getCurrentInstance, ref, onMounted, onUnmounted, computed } from "vue";
import { getThemeValue } from "@/utils/theme_utils.ts";
import { useThemeChart } from "@/hooks/useThemeChart.ts";

const { proxy } = getCurrentInstance()!;
const hot_ref = ref();
const allData = ref([]);
const echartsInstance = ref(null);
const curIndex = ref(0); // 当前所展示出的一级分类数据
const titleFontSize = ref(0);

const catName = computed(() => {
  if (allData.value.length === 0 || curIndex.value < 0 || curIndex.value >= allData.value.length) {
    return "";
  }
  return allData.value[curIndex.value].name;
});

const comStyle = computed(() => {
  return {
    fontSize: `${titleFontSize.value}px`,
    color: getThemeValue(themeStore.theme).labelColor
  };
});

// 初始化echartsInstance对象
const initChart = () => {
  echartsInstance.value = proxy!.$echarts.init(hot_ref.value, themeStore.theme);
  // 对图表初始化配置的控制
  const initOption = {
    title: {
      text: "▎ 热销商品占比",
      left: 20,
      top: 20
    },
    legend: {
      top: "12%",
      icon: "circle"
    },
    backgroundColor: getThemeValue(themeStore.theme).bgColor,
    tooltip: {
      show: true,
      formatter: arg => {
        const thirdCategory = arg.data.children;
        // 计算出所有三级分类的数值总和
        let total = 0;
        thirdCategory.forEach(item => {
          total += item.value;
        });
        let retStr = "";
        thirdCategory.forEach(item => {
          retStr += `${item.name}：${((item.value / total) * 100).toFixed(1) + "%"}<br>`;
        });
        return retStr;
      }
    },
    series: [
      {
        type: "pie",
        label: {
          show: false
        },
        emphasis: {
          label: {
            show: true
          },
          labelLine: {
            show: false
          }
        }
      }
    ]
  };
  echartsInstance.value.setOption(initOption);
};

// 获取服务器的数据
const getData = async res => {
  allData.value = res;
  if (allData.value.length > 0) {
    curIndex.value = 0;
  }
  updateChart();
};

// 更新图表
const updateChart = () => {
  const legendData = allData.value[curIndex.value].children.map(item => {
    return item.name;
  });
  const seriesData = allData.value[curIndex.value].children.map(item => {
    return {
      name: item.name,
      value: item.value,
      children: item.children
    };
  });
  const dataOption = {
    legend: {
      data: legendData
    },
    series: [
      {
        data: seriesData
      }
    ]
  };
  echartsInstance.value.setOption(dataOption);
};

const screenAdapter = () => {
  titleFontSize.value = (hot_ref.value.offsetWidth / 100) * 3.6;
  // 和分辨率大小相关的配置项(适配文字标题的大小)
  const adapterOption = {
    title: {
      textStyle: {
        fontSize: titleFontSize.value
      }
    },
    legend: {
      itemWidth: titleFontSize.value,
      itemHeight: titleFontSize.value,
      itemGap: titleFontSize.value / 2,
      textStyle: {
        fontSize: titleFontSize.value / 2
      }
    },
    series: [
      {
        radius: titleFontSize.value * 4,
        center: ["50%", "50%"]
      }
    ]
  };
  echartsInstance.value.setOption(adapterOption);
  // 手动的调用图表对象的resize 才能产生效果
  echartsInstance.value.resize();
};

const toLeft = () => {
  curIndex.value--;
  if (curIndex.value < 0) {
    curIndex.value = allData.value.length - 1;
  }
  updateChart();
};

const toRight = () => {
  curIndex.value++;
  if (curIndex.value > allData.value.length - 1) {
    curIndex.value = 0;
  }
  updateChart();
};

const { themeStore } = useThemeChart(echartsInstance, initChart, updateChart, screenAdapter);

onMounted(() => {
  // 注册回调（使用可选链操作符）
  proxy.$socket.registerCallBack("hotData", getData);
  initChart();
  proxy.$socket.send({
    action: "getData",
    socketType: "hotData",
    chartName: "hot",
    value: ""
  });
  window.addEventListener("resize", screenAdapter);
  // 在页面加载完成的时候, 主动进行屏幕的适配
  screenAdapter();
});

onUnmounted(() => {
  // 在组件销毁的时候, 需要将监听器取消掉
  window.removeEventListener("resize", screenAdapter);
  // 注销回调（使用可选链操作符）
  proxy.$socket.unRegisterCallBack("hotData");
});
defineExpose({
  screenAdapter
});
</script>
<style lang="scss" scoped>
.arr-left {
  position: absolute;
  left: 10%;
  top: 50%;
  transform: translateY(-50%);
  cursor: pointer;
}
.arr-right {
  position: absolute;
  right: 10%;
  top: 50%;
  transform: translateY(-50%);
  cursor: pointer;
}
.cat-name {
  position: absolute;
  left: 80%;
  bottom: 5%;
}
</style>
